package com.fatsatsuma.email;

import java.util.ArrayList;
import java.util.List;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import org.apache.log4j.Logger;

public abstract class AbstractTemplateHandler {

	private Logger log = Logger.getLogger(this.getClass());

	/**
	 * Method returns a parsed InternetAddress from the input string The input
	 * string is parsed with the supplied context
	 * 
	 * @param input
	 * @param context
	 * @return the parsed internet address
	 * @throws AddressException
	 *           if the input is null or the format of the address does not match
	 */
	protected InternetAddress getAddressFromString(String input, IContext context)
			throws AddressException {
		if (input == null) {
			throw new AddressException("Cannot create address from null input");
		}
		return new InternetAddress(evaluateString(input.trim(), context));
	}

	/**
	 * Method converts a list of string email address into a list of parsed, valid
	 * email addresses
	 * 
	 * @param addressesAsStrings
	 * @param context
	 * @return a list of email addresses
	 */
	protected List<InternetAddress> convertToInternetAddresses(List<String> addressesAsStrings,
			IContext context) {
		List<InternetAddress> addresses = new ArrayList<InternetAddress>();
		for (String addressAsString : addressesAsStrings) {
			try {
				addresses.add(getAddressFromString(addressAsString, context));
			} catch (AddressException exp) {
				log.error("Unable to add address : " + addressAsString);
			}
		}
		return addresses;
	}

	/**
	 * This method should parse an input string with the supplied context,
	 * replacing the embedded tags with content
	 * 
	 * @param input
	 * @param context
	 * @return the parsed result
	 */
	protected abstract String evaluateString(String input, IContext context);
}
